<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\information\Led as InformationLed;
use Exception;

/**
 * LED接口
 */
class Led extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $model = null;
    
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new InformationLed();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
    }

    /**
     * 详情
     */
    public function setLedOn()
    {
        $params = $this->request->param();
        try{
            $color = $this->model::setLedOn($params);
        }catch(Exception $e){
           trace(['亮灯失败原因',$e->getMessage()],'error');
           $this->error($e->getMessage());
        }
        $this->success('操作成功',[
            'color' => $color
        ]);
    }

    public function autoCloseLed(){
        $now = time();
        $shelves_id = db('led')
        ->whereRaw("output='ON' and (start_time+during)<={$now}")
        ->column('shelves_id','id');
        
        if($shelves_id){
            try{
                $ids = array_keys($shelves_id);
                $shelves_id = array_unique($shelves_id);//去重
                
                $this->model::lightOff($shelves_id);
                $this->model->where([
                    'id' => ['IN',$ids]
                ])
                ->delete();
            }catch(Exception $e){
               trace(['auto灭灯失败原因',$e->getMessage()],'error');
               $this->error($e->getMessage());
            }
            $this->success();
        }else{
            echo 'nodata';
        }
    }
}
